package cn.usian.jyzx.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.usian.common.exception.JyzxException;
import cn.usian.common.exception.LoginException;
import cn.usian.jyzx.common.util.SmsUtil;
import cn.usian.jyzx.model.dto.UserLoginDto;
import cn.usian.jyzx.model.dto.UserRegisterDto;
import cn.usian.jyzx.model.entity.user.UserInfo;
import cn.usian.jyzx.model.constant.Constant;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import cn.usian.jyzx.user.mapper.UserInfoMapper;
import cn.usian.jyzx.user.service.UserService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 11 05 08 59
 **/

@Service
@Slf4j
public class UserServiceImpl implements UserService {


    @Autowired

    RedisTemplate redisTemplate;
             @Autowired
    UserInfoMapper userInfoMapper;
    @Override
    public void sendCode(String phone) throws Exception {
        //生成随机数
        int code = RandomUtil.randomInt(1000, 10000);

        log.info("生成随机数:{}",code);
        //发送短信
        SmsUtil.sendSms(phone,code+"");
        //存入redis，code 有效期，key set
        //redis 基本数据类型：String List Set Zset hash
        //key：手机号 USER:REGISTER:CODE:132
        //value：验证码code

        redisTemplate.opsForValue().set(Constant.USER_CODE_KEY+phone,code+"",5, TimeUnit.MINUTES);


    }

    /**
     * 1:校验验证码:user code 和 redis code
     * 2：OK：save
     * 3：no OK：1： boolean
     *           2：
     *
     *           // return :程序终止
     *           //抛异常:程序终止；返回
     *           //拦截异常：JyzxException--》return
     *
     *
     * @param userRegisterDto
     */
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        String userCode = userRegisterDto.getCode();
        String phone = userRegisterDto.getUsername();
        String  redisCode = (String)redisTemplate.opsForValue().get(Constant.USER_CODE_KEY + phone);
        if(!userCode.equals(redisCode)){
            //自定义异常
            throw  new JyzxException(ResultCodeEnum.VERIFICATION_CODE_SERROR);
        }
        String newPasswrod = DigestUtils.md5DigestAsHex(userRegisterDto.getPassword().getBytes());

        log.info("密码明文：{}",userRegisterDto.getPassword());
          log.info("密码密文：{}",newPasswrod);
        //save
        UserInfo userInfo = new UserInfo();
             userInfo.setUsername(userRegisterDto.getUsername());
             userInfo.setPassword(newPasswrod);
                 userInfo.setPhone(userRegisterDto.getUsername());
                 userInfo.setSex(1);
                 userInfo.setAvatar("https://img10.360buyimg.com/pop/s1180x940_jfs/t1/226091/13/8500/93547/658d3b59F01b1f7ac/e835e81062f5ca73.jpg");

        userInfoMapper.saveUser(userInfo);

    }

    @Override
    public String login(UserLoginDto userLoginDto) {

        //1:先根据用户名去查数据库
        UserInfo userInfo = userInfoMapper.findByUsername(userLoginDto.getUsername());
        log.info("userInfo:{}",JSON.toJSONString(userInfo));
        if(null==userInfo)    {
            throw new LoginException   (ResultCodeEnum.USER_NOT_EXIST) ;
        }

        //用户输入的明文
        String password = userLoginDto.getPassword();
        //数据库的密文
        String password1 = userInfo.getPassword();

        String newPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        log.info("用户输入的明文:{},数据库的密文  :{},再次加密的密文：{}",password,password1,newPassword);

         //2:判断密码是否正确
        if(!password1.equals(newPassword))  {
               throw new LoginException   (ResultCodeEnum.USER_PASSWORD_ERROR) ;
        }

       // 3:生成token
        String token = UUID.randomUUID().toString();
        log.info("login token:{}",token);

        //4:存入到redis  key：token，value：user        USER:LOGIN:123
        redisTemplate.opsForValue().set(Constant.LOGIN_TOKEN_KEY+token, JSON.toJSONString(userInfo),2,TimeUnit.HOURS);



        //1。1：没有该用户， 抛异常，提示
        //1。2：有该用户，判断密码是否正确，不正确，抛异常，提示


        return token;
    }

    @Override
    public UserInfo getCurrentUserInfo(String token) {
        log.info("getCurrentUserInfo token:{}",token);
        String userInfoStr = (String)redisTemplate.opsForValue().get(Constant.LOGIN_TOKEN_KEY+token) ;
        log.info("userInfoStr:{}",userInfoStr);
        if(StringUtils.isEmpty(userInfoStr)){
            throw  new LoginException(ResultCodeEnum.LOGIN_AUTH_ERROR);
        }
           //json 字符串转成 UserInfo对象
        UserInfo userInfo = JSON.parseObject(userInfoStr,UserInfo.class);


        return userInfo;
    }
}
